package net.hualisheng.netty.service;

import net.hualisheng.netty.process.Processor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 多线程反应堆(Reactor) 模式
 *
 * @author lsy
 */
public class NioMultiServer {

    public  void main(String[] ags) {
        try {
            Selector selector = Selector.open();

            ServerSocketChannel channel = ServerSocketChannel.open();
            channel.configureBlocking(false);
            channel.bind(new InetSocketAddress(8088));
            channel.register(selector, SelectionKey.OP_ACCEPT);

            while (true) {
                System.out.println("轮询中。。。。");
                if (selector.selectNow() < 0) {
                    System.out.println("目前没有请求。。。");
                    continue;
                }
                Set<SelectionKey> keys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    System.out.println("进请求了..");
                    SelectionKey key = iterator.next();
                    if (key.isAcceptable()) {
                        ServerSocketChannel socketChannel = (ServerSocketChannel) key.channel();
                        SocketChannel acceptChannel = socketChannel.accept();
                        acceptChannel.configureBlocking(false);
                        SelectionKey readKey = acceptChannel.register(selector, SelectionKey.OP_READ);
                        readKey.attach(new MultiReactor());

                    }else if (key.isReadable()){
                        Processor attachment = (Processor) key.attachment();
                        attachment.process(key);
                    }

                }

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
